package com.hm.PushCaseService.service.ydcg.authentication;

import com.alibaba.fastjson2.JSON;
import com.hm.PushCaseService.constant.ReqUrl;
import com.hm.PushCaseService.pojo.ydcg.AccessTokenBean;
import com.hm.PushCaseService.pojo.ydcg.AuthorizationParamsBean;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * 英德城管-鉴权服务
 */

@Service
public class AuthenticationService implements IAuthentication {
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationService.class);

    @Qualifier("OkHttpClient")
    public OkHttpClient okHttpClient;

    public AuthenticationService(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @Override
    public String getToken() {
        //请求参数
        AuthorizationParamsBean paramsBean = new AuthorizationParamsBean();
        paramsBean.client_id = "10001";
        paramsBean.client_secret = "dd91a0180a";
        paramsBean.grant_type = "client_credentials";
        String reqParams = JSON.toJSONString(paramsBean);
        //构建请求体
        RequestBody body = RequestBody.create(reqParams, MediaType.get("application/json; charset=UTF-8"));
        Request request = new Request.Builder()//
                .url(ReqUrl.ReqTokenUrl)//请求连接
                .post(body)//请求体
                .build();//构建
        //同步请求
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody resBody = response.body();
            if (resBody != null) {
                String jsonString = resBody.string();
                AccessTokenBean accessTokenBean = JSON.parseObject(jsonString, AccessTokenBean.class);
                String token = accessTokenBean.access_token;
                logger.warn("获取英德城管accessToke成功：" + token);
                return token;
            } else {
                logger.error("accessToke获取失败onResponse为null！！ ");
            }
        } catch (Exception e) {
            logger.error("accessToke获取失败Exception: " + e.getMessage());
        }
        return "";
    }
}
